package com.example.mvicore.ui


import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment

abstract class BaseActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (isLayoutViewModel()){
            setContentView(generateLayoutView())
        }else{
            setContentView(generateLayoutId())
        }

        initView()
        initData()
        initEvent()
    }

    private fun generateLayoutId():Int{
        return 0;
    }

    abstract fun generateLayoutView():View

    protected fun isLayoutViewModel():Boolean{
        return true
    }

    protected open fun initView(){

    }

    protected open fun initData(){

    }

    protected open fun initEvent(){

    }

    /**
     * 提示信息
     */
    fun showMsg(msg:String){
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show()
    }

    /**
     * 路由跳转
     */
    fun router(target:Class<*>){
        startActivity(Intent(this,target))
    }

    /**
     * 路由携带参数跳转
     */
    fun router(target: Class<*>,param:Bundle){
        val intent = Intent(this,target)
        intent.putExtra("params",param)
        startActivity(intent)
    }

    /**
     * 添加fragment
     */
    fun addFragment(fragment:Fragment,tag:String){
        //防止在activity销毁时，fragment没添加进来，所以commitAllowingStateLoss()监听activity的生命周期
        supportFragmentManager.beginTransaction().add(fragment,tag).commitAllowingStateLoss()
    }
}